/**
 * @author:linjiye
 * @date: 2025/2/24
 * @desc:
 **/

import React, { useState } from 'react';
import {Button, Platform, Text, View,StyleSheet} from 'react-native';
import * as AuthSession from 'expo-auth-session';
import * as WebBrowser from 'expo-web-browser';

// 微信开放平台的 AppID
const WECHAT_APP_ID = 'wx10684715b8f3b501';
// 微信授权登录的回调地址，需要在微信开放平台上配置
const REDIRECT_URI = 'https://jz.feichengjiaoyu.com/';

WebBrowser.maybeCompleteAuthSession();

const useProxy = Platform.select({ web: false, default: true });

const discovery = {
  authorizationEndpoint: 'https://open.weixin.qq.com/connect/qrconnect',
  tokenEndpoint: 'https://api.weixin.qq.com/sns/oauth2/access_token',
  revocationEndpoint: 'https://api.weixin.qq.com/sns/oauth2/revoke',
};


type Props = {}

const loginTest = (props: Props) => {
  const [request, response, promptAsync] = AuthSession.useAuthRequest(
      {
        clientId: WECHAT_APP_ID,
        scopes: ['snsapi_login'],
        redirectUri: AuthSession.makeRedirectUri({
          useProxy,
          path: REDIRECT_URI,
        }),
      },
      discovery
  );

  const [userInfo, setUserInfo] = useState(null);

  const handleLogin = async () => {
    const result = await promptAsync();
    if (result.type === 'success') {
      const { code } = result.params;
      // 使用 code 换取 access_token
      const tokenResponse = await fetch(
          `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${WECHAT_APP_ID}&secret=023520809bd680595ecec839c95b1159&code=${code}&grant_type=authorization_code`
      );
      const tokenData = await tokenResponse.json();
      const { access_token, openid } = tokenData;

      // 使用 access_token 和 openid 获取用户信息
      const userInfoResponse = await fetch(
          `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}`
      );
      const userData = await userInfoResponse.json();
      setUserInfo(userData);
    }
  };

  return (
      <View >
        <Button
            title="微信登录"
            disabled={!request}
            onPress={handleLogin}
        />
          {/*<Text onPress={handleLogin}>微信登录</Text>*/}
        {userInfo && (
            <View>
              <Text>昵称: {userInfo.nickname}</Text>
              <Text>性别: {userInfo.sex === 1 ? '男' : '女'}</Text>
              <Text>城市: {userInfo.city}</Text>
            </View>
        )}
      </View>
  );
}

export default loginTest

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
    },
})